"use strict";

var gulp = require("gulp"),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    merge = require("merge-stream"),
    runSequence = require('run-sequence'),
    bundleconfig = require('./bundleconfig.json')

var regex = {
    css: /\.css$/,
    js: /\.js$/
};

gulp.task('min:js',function() {
    var tasks = getBundles(regex.js).map(function (bundle) {
        var outputFileName = getOutputFileName(bundle.outputFileName);
        var outputFolder = getOutputFolder(bundle.outputFileName);

        return gulp.src(bundle.inputFiles)
            .pipe(concat(outputFileName))
            .pipe(uglify())
            .pipe(gulp.dest(outputFolder));
    });

    return merge(tasks);
});

gulp.task('build', [], function () {
    runSequence(
        ['min:js']
    );
});

function getBundles(regexPattern) {
    return bundleconfig.filter(function (bundle) {
        return regexPattern.test(bundle.outputFileName);
    });
}

function getOutputFileName(fullFilePath) {
    var lastIndexOfSlash = fullFilePath.lastIndexOf('/');
    return fullFilePath.substr(lastIndexOfSlash, fullFilePath.length - lastIndexOfSlash);
}

function getOutputFolder(fullFilePath) {
    var lastIndexOfSlash = fullFilePath.lastIndexOf('/');
    return fullFilePath.substr(0, lastIndexOfSlash);
}
